/**
 * 易驰护运 - EditCar
 * http://menger.me
 * 车辆添加/修改
 * @huanhaun
 */

'use strict';

import React from 'react';
import {
    Text,
    View,
    Keyboard,
    TextInput,
    StatusBar,
    StyleSheet,
    ScrollView,
    TouchableOpacity,
} from 'react-native';
import { LargePicture } from '../../components';

export default class EditCar extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: true,
            // 多选类型数据来源
            kindSource: [],
            dataSource: [
                { bond: '', title: '账号信息', type: Constants.TITLE, },
                { bond: 'emp_no', title: '车辆账号', data: '', placeholder: '请输入车辆账号(司机登录账号)', keyboardType: 'numeric', type: Constants.INPUT, },
                { bond: '', title: '', type: Constants.NULL, },
                { bond: '', title: '车辆信息', type: Constants.TITLE, },
                { bond: 'vehicle_number', title: '车牌号', data: '', placeholder: '请选择车牌号', type: Constants.CHOICE, },
                { bond: 'vehicle_type', title: '车辆类型', data: '', placeholder: '请选择车辆类型', type: Constants.CHOICE, },
                { bond: 'vehicle_discharge', title: '车辆排放标准', data: '', placeholder: '请选择车辆排放标准', type: Constants.CHOICE, },
                { bond: 'vehicle_weight', title: '车载重量', data: '', placeholder: '请输入车载重量', keyboardType: 'numeric', type: Constants.INPUT, },
                { bond: 'vehicle_head', title: '车头照片', data: '', bgImg: Images.img_uploadimg3, type: Constants.IMG, },
                { bond: 'vehicle_trailer', title: '挂车照片', data: '', bgImg: Images.img_uploadimg3, type: Constants.IMG, },
                { bond: 'vehicle_driving_head_license', title: '车头行驶证', data: '', bgImg: Images.img_uploadimg3, type: Constants.IMG, },
                { bond: 'vehicle_driving_head_license_validity', title: '车头行驶证有效期', data: '', type: Constants.TIME, },
                { bond: 'vehicle_driving_trailer_license', title: '挂车行驶证', data: '', bgImg: Images.img_uploadimg3, type: Constants.IMG, },
                { bond: 'vehicle_driving_trailer_license_validity', title: '挂车行驶证有效期', data: '', type: Constants.TIME, },
                { bond: 'vehicle_taxi_head_license', title: '车头运营证', data: '', bgImg: Images.img_uploadimg4, type: Constants.IMG, },
                { bond: 'vehicle_taxi_head_license_validity', title: '车头运营证有效期', data: '', type: Constants.TIME, },
                { bond: 'vehicle_taxi_trailer_license', title: '挂车运营证', data: '', bgImg: Images.img_uploadimg4, type: Constants.IMG, },
                { bond: 'vehicle_taxi_trailer_license_validity', title: '挂车运营证有效期', data: '', type: Constants.TIME, },
                { bond: 'vehicle_insurance_policy', title: '保险单', data: '', bgImg: Images.img_uploadimg1, type: Constants.IMG, },
                { bond: 'vehicle_insurance_policy_validity', title: '保险单有效期', data: '', type: Constants.TIME, },
                { bond: '', title: '', type: Constants.NULL, },

                { bond: '', title: '司机信息', type: Constants.TITLE, },
                { bond: 'driver_name', title: '司机姓名', data: '', placeholder: '请输入司机姓名', keyboardType: 'default', type: Constants.INPUT, },
                { bond: 'driver_mobile', title: '司机联系方式', data: '', placeholder: '请输入司机联系方式', keyboardType: 'numeric', type: Constants.INPUT, },
                { bond: 'driver_identity_card', title: '身份证正面', data: '', bgImg: Images.img_uploadimg2, type: Constants.IMG, },
                { bond: 'driver_identity_card_h', title: '身份证反面', data: '', bgImg: Images.img_uploadimg2, type: Constants.IMG, },
                { bond: 'driver_identity_card_validity', title: '身份证有效期', data: '', type: Constants.TIME, },
                { bond: 'driver_drivers_license', title: '驾驶证', data: '', bgImg: Images.img_uploadimg3, type: Constants.IMG, },
                { bond: 'driver_drivers_license_validity', title: '驾驶证有效期', data: '', type: Constants.TIME, },
                { bond: 'driver_qualification_certificate', title: '从业资格证类别 (危险货物运输驾驶员证)', data: '', bgImg: Images.img_uploadimg5, type: Constants.IMG, },
                { bond: 'driver_qualification_certificate_validity', title: '从业资格证有效期', data: '', type: Constants.TIME, },
                { bond: '', title: '', type: Constants.NULL, },

                { bond: '', title: '押运员信息', type: Constants.TITLE, },
                { bond: 'supercargo_name', title: '押运员姓名', data: '', placeholder: '请输入押运员姓名', keyboardType: 'default', type: Constants.INPUT, },
                { bond: 'supercargo_mobile', title: '押运员联系方式', data: '', placeholder: '请输入押运员联系方式', keyboardType: 'numeric', type: Constants.INPUT, },
                { bond: 'supercargo_identity_card', title: '身份证正面', data: '', bgImg: Images.img_uploadimg2, type: Constants.IMG, },
                { bond: 'supercargo_identity_card_h', title: '身份证反面', data: '', bgImg: Images.img_uploadimg2, type: Constants.IMG, },
                { bond: 'supercargo_identity_card_validity', title: '身份证有效期', data: '', type: Constants.TIME, },
                { bond: 'supercargo_drivers_license', title: '押运员证', data: '', bgImg: Images.img_uploadimg3, type: Constants.IMG, },
                { bond: 'supercargo_drivers_license_validity', title: '押运员证有效期', data: '', type: Constants.TIME, },
                { bond: 'supercargo_qualification_certificate', title: '从业资格证类别 (危险货物运输押运员证)', data: '', bgImg: Images.img_uploadimg5, type: Constants.IMG, },
                { bond: 'supercargo_qualification_certificate_validity', title: '从业资格证有效期', data: '', type: Constants.TIME, },
                { bond: '', title: '', type: Constants.NULL, },
            ],
            // 这两个选择项在提交时需要提交key
            vehicle_type: '',
            vehicle_discharge: '',
        }
    }

    componentDidMount () {
        this.requestData();
        
    }

    // 请求一些多选类可供选择的数据
    requestData = async () => {
        let url = ServicesApi.SETUP_CONFIG_LIST;
        let data = {};
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({kindSource: result.data}, () => this.setData());
        }
    }

    // 请求之前的数据
    setData = async () => {
        let {item} = this.params;
        if (!item) { 
            this.setState({loading: false})
            return 
        }
        let {kindSource} = this.state;
        let url = ServicesApi.PERSONAL_CENTER_VEHICLE_INFO;
        let data = { id: item.id };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let vehicle_type = '', vehicle_discharge = '';
            kindSource.vehicle_type_text.map((_item) => {
                if (result.data.vehicle_type == _item.key) {
                    vehicle_type = _item.key
                    this.updateState('vehicle_type', _item.val)
                }
            })
            kindSource.vehicle_discharge_text.map((_item) => {
                if (result.data.vehicle_discharge == _item.key) {
                    vehicle_discharge = _item.key
                    this.updateState('vehicle_discharge', _item.val)
                }
            })
            this.updateState('emp_no', result.data.emp_no)
            this.updateState('vehicle_number', result.data.vehicle_number)
            this.updateState('vehicle_weight', result.data.vehicle_weight)
            this.updateState('vehicle_head', result.data.vehicle_head)
            this.updateState('vehicle_trailer', result.data.vehicle_trailer)
            this.updateState('vehicle_driving_head_license', result.data.vehicle_driving_head_license)
            this.updateState('vehicle_driving_head_license_validity', result.data.vehicle_driving_head_license_validity)
            this.updateState('vehicle_driving_trailer_license', result.data.vehicle_driving_trailer_license)
            this.updateState('vehicle_driving_trailer_license_validity', result.data.vehicle_driving_trailer_license_validity)
            this.updateState('vehicle_taxi_head_license', result.data.vehicle_taxi_head_license)
            this.updateState('vehicle_taxi_head_license_validity', result.data.vehicle_taxi_head_license_validity)
            this.updateState('vehicle_taxi_trailer_license', result.data.vehicle_taxi_trailer_license)
            this.updateState('vehicle_taxi_trailer_license_validity', result.data.vehicle_taxi_trailer_license_validity)
            this.updateState('vehicle_insurance_policy', result.data.vehicle_insurance_policy)
            this.updateState('vehicle_insurance_policy_validity', result.data.vehicle_insurance_policy_validity)
            this.updateState('driver_name', result.data.driver_name)
            this.updateState('driver_mobile', result.data.driver_mobile)
            this.updateState('driver_identity_card', result.data.driver_identity_card)
            this.updateState('driver_identity_card_h', result.data.driver_identity_card_h)
            this.updateState('driver_identity_card_validity', result.data.driver_identity_card_validity)
            this.updateState('driver_drivers_license', result.data.driver_drivers_license)
            this.updateState('driver_drivers_license_validity', result.data.driver_drivers_license_validity)
            this.updateState('driver_qualification_certificate', result.data.driver_qualification_certificate)
            this.updateState('driver_qualification_certificate_validity', result.data.driver_qualification_certificate_validity)
            this.updateState('supercargo_name', result.data.supercargo_name)
            this.updateState('supercargo_mobile', result.data.supercargo_mobile)
            this.updateState('supercargo_identity_card', result.data.supercargo_identity_card)
            this.updateState('supercargo_identity_card_h', result.data.supercargo_identity_card_h)
            this.updateState('supercargo_identity_card_validity', result.data.supercargo_identity_card_validity)
            this.updateState('supercargo_drivers_license', result.data.supercargo_drivers_license)
            this.updateState('supercargo_drivers_license_validity', result.data.supercargo_drivers_license_validity)
            this.updateState('supercargo_qualification_certificate', result.data.supercargo_qualification_certificate)
            this.updateState('supercargo_qualification_certificate_validity', result.data.supercargo_qualification_certificate_validity)
            console.log('vehicle_type.key------------->', vehicle_type.key)
            console.log('vehicle_discharge.key------------->', vehicle_discharge.key)
            this.setState({
                vehicle_type: vehicle_type,
                vehicle_discharge: vehicle_discharge,
                loading: false,
            })
        }
    }

    // 把数据插进dataSource
    updateState = (bond, data, showData, refresh) => {
        let { dataSource } = this.state;
        let index = dataSource.findIndex((item) => item.bond === bond);
        if (index !== -1) {
            let newItem = dataSource[index];
            newItem['data'] = data;
            newItem['showData'] = showData ? showData : data;
            if (refresh) {
                let newDataSource = dataSource.slice();
                newDataSource[index] = newItem;
                this.setState({ dataSource: newDataSource });
            } else {
                dataSource[index] = newItem;
            }
        }
    };

    // 车牌选择
    carNumberPicker = (data) => {
        Keyboard.dismiss();
        let params = {
            defaultData: data,
            onPress: (value) => {
                this.updateState('vehicle_number', value.num.join(''))
                this.setState({}) // 为了刷新下
            },
            option: {
                panGestureEnabled: false,
            }
        }
        ActionManager.showCarNumberPicker(params);
    };

    // 单选类型
    onPressChoice = (type) => {
        let {kindSource} = this.state;
        let dataList = [];
        if (type === 'vehicle_type') {
            dataList = kindSource.vehicle_type_text
        } else if (type === 'vehicle_discharge') {
            dataList = kindSource.vehicle_discharge_text
        }
        let actions = Array.isArray(dataList) && dataList.map((item) => {
            return {
                title: item.val,
                onPress: () => {
                    if (type === 'vehicle_type') {
                        this.updateState(type, item.val)
                        this.setState({vehicle_type: item.key})
                    } else if (type === 'vehicle_discharge') {
                        this.updateState(type, item.val)
                        this.setState({vehicle_discharge: item.key})
                    }
                    ActionManager.hide()
                }
            }
        });
        let params = {
            actions,
            option: { panGestureEnabled: false }
        }
        ActionManager.show(params);
    }

    // 上传图片
    onPressUpImg = async (type) => {
        let _result = await MediaManager.showActionPicker({
            includeBase64: true,
        });
        if (_result && _result.code === StatusCode.SUCCESS_CODE) {
            ToastManager.loading('上传中...', {duration: 9999999});
            const upRes = await Services.uploadQiNiu(_result.data);
            if (upRes.code === StatusCode.SUCCESS_CODE) {
                ToastManager.hide();
                ToastManager.success('上传成功');
                this.updateState(type, ServicesApi.QI_NIU_HOST + upRes.data[0].key)
                this.setState({})
            } else {
                ToastManager.fail('上传失败');
            }
        }
    };

    // 删除图片
    deleteImg = async (type) => {
        this.updateState(type, '')
        this.setState({})
    }

    // 时间选择
    showActionPicker = (type) => {
        let params = {
            onPress: (value) => {
                let date = value.year+'-'+value.month+'-'+value.day;
                this.updateState(type, date)
                this.setState({})
            }
        }
        ActionManager.showWheelDate(params);
    };

    onSubmit = async () => {
        Keyboard.dismiss();
        let { item, onRefresh } = this.params;
        let { dataSource, vehicle_type, vehicle_discharge } = this.state;
        let url = '';
        url = (item && item.id) ? ServicesApi.PERSONAL_CENTER_DRIVER_RE_REG : ServicesApi.LOGIN_DRIVER_REG;
        console.log('url------------->', url)
        let data = {};
        dataSource.forEach((_item) => {
            if (_item.type === Constants.TITLE || _item.type === Constants.NULL) {
                // 不需要返回什么
            } else if (_item.bond === 'vehicle_type') {
                data['vehicle_type'] = vehicle_type
            } else if (_item.bond === 'vehicle_discharge') {
                data['vehicle_discharge'] = vehicle_discharge
            } else {
                data[_item.bond] = _item.data
                if ( item && item.id ) {
                    data['id'] = item.id
                }
            }
        });
        let result = await Services.post(url, data);
        if (result.code == StatusCode.SUCCESS_CODE) {
            ToastManager.success(result.msg);
            onRefresh && onRefresh();
            setTimeout(() => {
                RouterHelper.goBack();
            }, 1000);
        } else if (result.code === StatusCode.FAIL_CODE) {
            ToastManager.warn(result.msg)
        }
    }


    bodyView = () => {
        let {dataSource} = this.state;
        let body = Array.isArray(dataSource) && dataSource.map((item, index) => {
            switch (item.type) {
                case Constants.TITLE:
                    return (
                        <View key={index} style={styles.cardBox}>
                            <View style={styles.cardHeader}>
                                <View style={styles.cardHeaderBall}><View style={styles.cardHeaderBallCenter}/></View>
                                <Text style={styles.cardHeaderText}>{item.title}</Text>
                            </View>
                        </View>
                    )
                    break;
                case Constants.NULL:
                    return (
                        <View key={index} style={styles.nullLine}/>
                    )
                    break;
                case Constants.INPUT:
                    return (
                        <View key={index} style={styles.cardBox}>
                            <View style={styles.cardLine}>
                                <Text style={styles.lineLeft}>{item.title}</Text>
                                <TextInput
                                    defaultValue={item.data}
                                    style={styles.lineInput}
                                    placeholder={item.placeholder}
                                    placeholderTextColor={'#999'}
                                    onChangeText={(text) => this.updateState(item.bond, text)}
                                    keyboardType={item.keyboardType}
                                />
                            </View>
                        </View>
                    )
                    break;
                case Constants.CHOICE:
                    let onPress = {};
                    switch (item.bond) {
                        case 'vehicle_number':
                            onPress = () => this.carNumberPicker(item.data)
                            break;
                        case 'vehicle_type':
                            onPress = () => this.onPressChoice('vehicle_type')
                            break;
                        case 'vehicle_discharge':
                            onPress = () => this.onPressChoice('vehicle_discharge')
                            break;
                        default:
                            break;
                    }
                    return (
                        <View key={index} style={styles.cardBox}>
                            <View style={styles.cardLine}>
                                <Text style={styles.lineLeft}>{item.title}</Text>
                                <Text 
                                    numberOfLines={1} 
                                    style={[styles.lineInput, item.data === '' && {color: '#999'}]} 
                                    onPress={onPress}
                                >
                                    {item.data || item.placeholder}
                                </Text>
                                <ImageView
                                    resizeMode={'contain'}
                                    style={styles.arrow}
                                    source={Images.icon_arrow_right}
                                />
                            </View>
                        </View>
                    )
                    break;
                case Constants.IMG:
                    return (
                        <View key={index} style={styles.cardBox}>
                            <View style={[styles.cardLine, styles.heightLine]}>
                                <Text style={styles.lineLeft}>{item.title}</Text>
                                <TouchableOpacity onPress={() => this.onPressUpImg(item.bond)}>
                                    {
                                        item.data
                                        ?   <View>
                                                <LargePicture resizeMode={'cover'} style={styles.lineImg} imageStyle={styles.lineImg} source={{uri: item.data}}/> 
                                                <TouchableOpacity style={styles.deleteImgBox} onPress={() => this.deleteImg(item.bond)}>
                                                    <ImageView resizeMode={'contain'} style={styles.deleteImg} source={Images.icon_result_fail}/>
                                                </TouchableOpacity>
                                            </View>
                                        :   <ImageView resizeMode={'contain'} style={styles.lineImg} source={item.bgImg}/>  
                                    }
                                </TouchableOpacity>
                            </View>
                        </View>
                    )
                    break;
                case Constants.TIME:
                    return (
                        <View key={index} style={styles.cardBox}>
                            <View style={styles.cardLine}>
                                <Text style={styles.lineLeft}>{item.title}</Text>
                                <Text
                                    onPress={() => this.showActionPicker(item.bond)}
                                    style={[styles.lineInput, item.data == '' && {color: '#999'}]} 
                                >
                                    {item.data || item.placeholder}
                                </Text>
                                <ImageView
                                    resizeMode={'contain'}
                                    style={styles.arrow}
                                    source={Images.icon_arrow_right}
                                />
                            </View>
                        </View>
                    )
                    break;
                default:
                    break;
            }
        })
        return body
    }

    render() {
        let {loading} = this.state;
        let pageTitle = this.params.pageTitle || '添加车辆'
        return (
            <PageContainer
                loading={loading}
                fitIPhoneX={true} 
                style={styles.container}
            >
                <NavigationBar title={pageTitle}/>
                <ScrollView>
                    {this.bodyView()}
                </ScrollView>
                <View style={styles.btnBox}>
                    <Button
                        style={styles.btn}
                        title={'提交审核'}
                        titleStyle={styles.btnTitle}
                        resizeMode={'cover'}
                        backgroundImage={Images.img_btn_bg1}
                        onPress={() => this.onSubmit()}
                    />    
                </View>
            </PageContainer>
        )
    }
}

const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    // 整体
    container: {
        backgroundColor: '#f2f2f2',
    },
    cardBox: {
        backgroundColor: '#fff',
        paddingHorizontal: 15,
    },
    // 卡片
    cardHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 50,
    },
    cardHeaderBall: {
        width: 12,
        height: 12,
        borderRadius: 6,
        backgroundColor: DominantColor,
        marginRight: 6,
        alignItems: 'center',
        justifyContent: 'center',
    },
    cardHeaderBallCenter: {
        height: 6,
        width: 6,
        borderRadius: 3,
        backgroundColor: '#fff',
    },
    cardHeaderText: {
        color: '#333',
        fontSize: 15,
        fontWeight: 'bold',
    },
    // 内容
    cardLine: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 50,
        borderTopWidth: Predefine.minPixel,
        borderColor: '#e1e1e1',
    },
    heightLine: {
        height: 90,
    },
    lineLeft: {
        flex: 1,
        color: '#333',
        fontSize: 14,
        marginRight: 6,
    },
    arrow: {
        width: 6,
        height: 10,
        marginLeft: 8,
    },
    codeBox: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    codeTextBox: {
        borderLeftWidth: 1,
        borderLeftColor: DominantColor,
        paddingLeft: 6,
        marginLeft: 6,
    },
    codeText: {
        color: DominantColor,
        fontSize: 14,
    },
    lineInput: {
        flex: 1,
        textAlign: 'right',
        color: '#333',
        fontSize: 14,
    },
    lineImg: {
        width: 100,
        height: 60,
    },
    deleteImgBox: {
        position: 'absolute',
        top: -8,
        right: -8,
        width: 20,
        height: 20,
        borderRadius: 10,
    },
    deleteImg: {
        width: 20,
        height: 20,
        borderRadius: 10,
        backgroundColor: '#fff',
    },
    // nullLine
    nullLine: {
        height: 10,
        backgroundColor: '#f2f2f2',
    },
    // 底部的按钮
    btnBox: {
        paddingHorizontal: 15,
        paddingVertical: 10,
        backgroundColor: '#fff',
    },
    btn: {
        backgroundColor: DominantColor,
    },
})